#!/usr/bin/php -q
<?PHP
/* Copyright 2005-2018, Lime Technology
 * Copyright 2012-2018, Bergware International.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License version 2,
 * as published by the Free Software Foundation.
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 */
?>
<?
$var   = parse_ini_file("/var/local/emhttp/var.ini");
$devs  = parse_ini_file("/var/local/emhttp/devs.ini",true);
$disks = parse_ini_file("/var/local/emhttp/disks.ini",true);

$docroot = $docroot ?? $_SERVER['DOCUMENT_ROOT'] ?: '/usr/local/emhttp';
require_once "$docroot/webGui/include/Wrappers.php";
require_once "$docroot/webGui/include/Preselect.php";
require_once "$docroot/webGui/include/CustomMerge.php";

$notify = "$docroot/webGui/scripts/notify";
$ram    = "/var/local/emhttp/monitor.ini";
$rom    = "/boot/config/plugins/dynamix/monitor.ini";
$saved  = @parse_ini_file($ram,true);
$unraid = parse_plugin_cfg("dynamix",true);
$high1  = $unraid['display']['critical'];
$high2  = $unraid['display']['warning'];
$server = strtoupper($var['NAME']);
$errors = [];
$top    = 120;

function plus($val,$word,$last) {
  return $val>0 ? (($val||$last) ? ($val.' '.$word.($val!=1?'s':'').($last ?'':', ')) : '') : '';
}
function my_temp($value) {
  global $unraid;
  $unit = $unraid['display']['unit'];
  return ($unit=='F' ? round(9/5*$value+32) : $value)." $unit";
}
function my_disk($name) {
  return ucfirst(preg_replace('/^(disk|cache|parity)(\d+)/','$1 $2',$name));
}
function my_scale($value, &$unit, $decimals=NULL, $scale=NULL) {
  global $unraid;
  $scale = $scale ?? $unraid['display']['scale'];
  $number = $unraid['display']['number'];
  $units = ['B','KB','MB','GB','TB','PB','EB','ZB','YB'];
  $size = count($units);
  if ($scale==0 && ($decimals===NULL || $decimals<0)) {
    $decimals = 0;
    $unit = '';
  } else {
    $base = $value ? floor(log($value, 1000)) : 0;
    if ($scale>0 && $base>$scale) $base = $scale;
    if ($base>$size) $base = $size-1;
    $value /= pow(1000, $base);
    if ($decimals===NULL) $decimals = $value>=100 ? 0 : ($value>=10 ? 1 : (round($value*100)%100===0 ? 0 : 2));
    elseif ($decimals<0) $decimals = $value>=100||round($value*10)%10===0 ? 0 : abs($decimals);
    if ($scale<0 && round($value,-1)==1000) {$value = 1; $base++;}
    $unit = $units[$base];
  }
  return number_format($value, $decimals, $number[0], $value>=10000 ? $number[1] : '');
}
function my_check($time,$speed) {
  if (!$time) return '不可用 (没有奇偶校验记录)';
  $days = floor($time/86400);
  $hmss = $time-$days*86400;
  $hour = floor($hmss/3600);
  $mins = $hmss/60%60;
  $secs = $hmss%60;
  return plus($days,'天',($hour|$mins|$secs)==0).plus($hour,'小时',($mins|$secs)==0).plus($mins,'分钟',$secs==0).plus($secs,'秒',true).". 平均速度: $speed";
}
function read_write_parity_log($epoch,$duration,$speed,$status,$error) {
  $log = '/boot/config/parity-checks.log';
  $timestamp = str_replace(['.0','.'],['  ',' '],date('M.d H:i:s',$epoch));
  if (file_exists($log)) {
    $handle = fopen($log, 'r');
    while (($line = fgets($handle))!==false) {
      if (strpos($line,$timestamp)!==false) break;
    }
    fclose($handle);
  }
  if (empty($line)) {
    $year = date('Y',$epoch);
    $line = "$year $timestamp|$duration|$speed|$status|$error";
    if ($status==0||file_exists($log)) file_put_contents($log,"$line\n",FILE_APPEND);
  }
  return str_replace("\n","",$line);
}
function check_temp($name,$temp,$text,$info) {
  global $notify,$disks,$saved,$unraid,$server,$top;
  $disk = &$disks[$name];
  $hot  = $disk['hotTemp'] ?? $unraid['display']['hot'];
  $max  = $disk['maxTemp'] ?? $unraid['display']['max'];
  $warn = exceed($temp,$max,$top) ? 'alert' : (exceed($temp,$hot,$top) ? 'warning' : '');
  $item = 'temp';
  $last = $saved[$item][$name] ?? 0;
  if ($warn) {
    if ($temp>$last) {
      exec("$notify -e ".escapeshellarg("Unraid $text 温度")." -s ".escapeshellarg(ucfirst($warn)." [$server] - $text ".($warn=='alert'?'过热 (':'很热 (').my_temp($temp).")")." -d ".escapeshellarg("$info")." -i \"$warn\"");
      $saved[$item][$name] = $max>0 && $temp<=$max ? $max : $temp;
    }
  } else {
    if ($last && $temp<=$top) {
      exec("$notify -e ".escapeshellarg("Unraid $text 消息")." -s ".escapeshellarg("通知 [$server] - $text 恢复正常温度")." -d ".escapeshellarg("$info"));
      unset($saved[$item][$name]);
    }
  }
}
function check_smart($name,$port,$text,$info) {
  global $var,$disks,$notify,$saved,$server,$numbers;
  $disk   = &$disks[$name];
  $select = get_value($disk,'smSelect',0);
  $level  = get_value($disk,'smLevel',1);
  $events = explode('|',get_value($disk,'smEvents',$numbers));
  $type   = get_value($disk,'smType','');
  get_ctlr_options($type, $disk);
  $file = "/var/local/emhttp/smart/$name";
  exec("awk 'NR>7{print $1,$2,$4,$6,$9,$10}' ".escapeshellarg($file)." 2>/dev/null", $codes);
  $item = 'smart';
  foreach ($codes as $code) {
    if (!$code || !is_numeric($code[0])) continue;
    list($id,$class,$value,$thres,$when,$raw) = explode(' ',$code);
    $fail = strpos($when,'FAILING_NOW')!==false;
    if (!$fail && !in_array($id,$events)) continue;
    $word = str_replace(['_',' (-)'],[' ',''],strtolower("$class ($when)"));
    $ack = "$name.ack";
    switch ($select) {
    case 0:
      $attr = "$name.$id";
      $last = ($saved[$item][$attr] ?? 0)*$level;
      if ($raw>0 || $fail) {
        if ($raw>$last) {
          exec("$notify -e ".escapeshellarg("Unraid $text SMART 健康 [$id]")." -s ".escapeshellarg("警告 [$server] - $word 为 $raw")." -d ".escapeshellarg("$info")." -i \"warning\"");
          $saved[$item][$attr] = $raw;
          unset($saved[$item][$ack]);
        }
      } else {
        if ($last>0) {
          exec("$notify -e ".escapeshellarg("Unraid $text SMART 消息 [$id]")." -s ".escapeshellarg("通知 [$server] - $word 恢复到正常值")." -d ".escapeshellarg("$info"));
          unset($saved[$item][$attr]);
          unset($saved[$item][$ack]);
        }
      }
      break;
    case 1:
      $attr = "$name.${id}n";
      $last = $saved[$item][$attr] ?? 255;
      if (($thres>0 && $value<=$thres*$level) || $fail) {
        if ($value*($value>$thres?$level:1)<$last) {
          exec("$notify -e ".escapeshellarg("Unraid $text SMART 健康 [$id]")." -s ".escapeshellarg("警告 [$server] - $word 为 $value")." -d ".escapeshellarg("$info")." -i \"warning\"");
          $saved[$item][$attr] = $value;
          unset($saved[$item][$ack]);
        }
      } else {
        if ($last<255) {
          exec("$notify -e ".escapeshellarg("Unraid $text SMART 消息 [$id]")." -s ".escapeshellarg("通知 [$server] - $word 恢复到正常值")." -d ".escapeshellarg("$info"));
          unset($saved[$item][$attr]);
          unset($saved[$item][$ack]);
        }
      }
      break;
    }
  }
  $file .= '.ssa';
  if (!file_exists($file) || (time()-filemtime($file)>$var['poll_attributes'])) exec("smartctl -n standby -H $type ".escapeshellarg("/dev/$port")."|grep -Pom1 '^SMART.*: \K[A-Z]+'|tr -d '\n' >".escapeshellarg($file));
}
function check_usage($name,$used,$text,$info) {
  global $notify,$disks,$saved,$unraid,$server;
  if ($used == -1) return;
  $disk = &$disks[$name];
  $warning = $disk['warning'] ?? $unraid['display']['warning'];
  $critical = $disk['critical'] ?? $unraid['display']['critical'];
  $warn = exceed($used,$critical) ? 'alert' : (exceed($used,$warning) ? 'warning' : '');
  $item = 'used';
  $last = $saved[$item][$name] ?? 0;
  if ($warn) {
    if ($used>$last) {
      exec("$notify -e ".escapeshellarg("Unraid $text 磁盘使用率")." -s ".escapeshellarg(ucfirst($warn)." [$server] - $text 为 ".($warn=='alert'?'空间不足':'使用率高')." (${used}%)")." -d ".escapeshellarg("$info")." -i \"$warn\"");
      $saved[$item][$name] = $critical>0 && $used<=$critical ? $critical : $used;
    }
  } else {
    if ($last && $used<=100) {
      exec("$notify -e ".escapeshellarg("Unraid $text 消息")." -s ".escapeshellarg("通知 [$server] - $text 使用率恢复正常")." -d ".escapeshellarg("$info"));
      unset($saved[$item][$name]);
    }
  }
}

// check array devices
foreach ($disks as $disk) {
  $name = $disk['name'];
  if ($name=='flash' || substr($disk['status'],-3)=='_NP') continue;
  $text = my_disk($name).($name=='cache'||$name=='parity'?' disk':'');
  $info = !empty($disk['id']) ? "{$disk['id']} ({$disk['device']})" : "无设备标识 ({$disk['device']})";
// process disk temperature notifications
  check_temp($name,$disk['temp'],$text,$info);
// process disk SMART notifications
  check_smart($name,port_name($disk['smDevice'] ?? $disk['device']),$text,$info);
// process disk usage notifications
  check_usage($name,isset($disk['fsSize'])&&$disk['fsSize']>0?100-round(100*$disk['fsFree']/$disk['fsSize']):-1,$text,$info);
// process disk operation notifications
  $warn = strtok($disk['color'],'-');
  $item = 'disk';
  $last = $saved[$item][$name] ?? '';
  switch ($warn) {
  case 'red':
    if ($warn!=$last) {
      $status = strtolower(str_replace(['NP_','_'],['',' '],$disk['status']));
      exec("$notify -e ".escapeshellarg("Unraid $text 错误")." -s ".escapeshellarg("注意 [$server] - $text 发生错误 ($status)")." -d ".escapeshellarg("$info")." -i \"alert\"");
      $saved[$item][$name] = $warn;
    }
  break;
  case 'yellow':
    if ($warn!=$last) {
      $status = $name=='parity' ? "正在进行奇偶同步" : "驱动器未就绪, 正在重建内容";
      exec("$notify -e ".escapeshellarg("Unraid $text 错误")." -s ".escapeshellarg("警告 [$server] - $text, $status")." -d ".escapeshellarg("$info")." -i \"warning\"");
      $saved[$item][$name] = $warn;
    }
  break;
  default:
    if ($last) {
      exec("$notify -e ".escapeshellarg("Unraid $text 消息")." -s ".escapeshellarg("通知 [$server] - $text 恢复正常运行")." -d ".escapeshellarg("$info"));
      unset($saved[$item][$name]);
    }
  break;}
// count disk errors
  if ($disk['numErrors']>0) $errors[] = "$text - $info (errors {$disk['numErrors']})";
// check file system of cache pool
  $item = 'pool';
  if ($name=='cache' && strpos($disk['fsType'],'btrfs')!==false) {
    $attr = 'missing';
    if (exec("/sbin/btrfs filesystem show {$disk['uuid']} 2>/dev/null|grep -c 'missing'")>0) {
      if (empty($saved[$item][$attr])) {
        exec("$notify -e ".escapeshellarg("Unraid $text 消息")." -s ".escapeshellarg("警告 [$server] - 缓存池 BTRFS 设备丢失")." -d ".escapeshellarg("$info")." -i \"warning\"");
        $saved[$item][$attr] = 1;
      }
    } elseif (isset($saved[$item][$attr])) unset($saved[$item][$attr]);
    $attr = 'profile';
    if (exec("/sbin/btrfs filesystem df /mnt/cache 2>/dev/null|grep -c '^Data'")>1) {
      if (empty($saved[$item][$attr])) {
        exec("$notify -e ".escapeshellarg("Unraid $text 消息")." -s ".escapeshellarg("警告 [$server] - 缓存池 BTRFS 文件太多 (在进行缓存池平衡操作时可以忽略此警告)")." -d ".escapeshellarg("$info")." -i \"warning\"");
        $saved[$item][$attr] = 1;
      }
    } elseif (isset($saved[$item][$attr])) unset($saved[$item][$attr]);
  }
}

// check unassigned devices
foreach ($devs as $dev) {
  $name = $dev['device'];
  $smart = "/var/local/emhttp/smart/$name";
  $type = $var['smType'] ?? '';
  $port = port_name($name);
  if (!file_exists($smart) || (time()-filectime($smart)>$var['poll_attributes'])) exec("smartctl -n standby -A $type ".escapeshellarg("/dev/$port")." >".escapeshellarg($smart));
  $temp = exec("awk 'BEGIN{s=t=\"*\"}\$1==190{s=\$10};\$1==194{t=\$10;exit};\$1==\"Temperature:\"{t=\$2;exit};/^Current Drive Temperature:/{t=\$4;exit} END{if(t!=\"*\")print t; else print s}' ".escapeshellarg($smart)." 2>/dev/null");
  $text = "device $name";
  $info = !empty($dev['id']) ? "{$dev['id']} ($name)": "无设备标识 ($name)";
// process disk temperature notifications
  check_temp($name,$temp,$text,$info);
// process disk SMART notifications
  check_smart($name,$port,$text,$info);
}

// report array read errors
$item = 'array';
$name = 'errors';
$last = $saved[$item][$name] ?? 0;
$warn = count($errors);
$info = "阵列 $warn 硬盘".($warn==1 ? "" : "")." 有读取错误";
if ($warn>0) {
  if ($warn<>$last) {
    $message = implode('\n', $errors);
    exec("$notify -e \"Unraid 阵列错误\" -s ".escapeshellarg("警告 [$server] - 阵列存在错误")." -d ".escapeshellarg("$info")." -m ".escapeshellarg("$message")." -i \"warning\"");
    $saved[$item][$name] = $warn;
  }
} else {
  if ($last) {
    exec("$notify -e \"Unraid 阵列错误\" -s ".escapeshellarg("通知 [$server] - 阵列恢复正常")." -d ".escapeshellarg("$info"));
    unset($saved[$item][$name]);
  }
}

// process parity check, parity sync and data-rebuild notifications
$name = 'parity';
$last = $saved[$item][$name] ?? '';
if ($var['mdResyncPos']) {
  if (!$last) {
    if (strstr($var['mdResyncAction'],"recon")) {
      $last = '奇偶同步/数据重建';
    } elseif (strstr($var['mdResyncAction'],"clear")) {
      $last = '磁盘清理';
    } elseif ($var['mdResyncAction']=="check") {
      $last = '读取检查';
    } elseif (strstr($var['mdResyncAction'],"check")) {
      $last = '奇偶校验';
    }
    $info = "大小: ".my_scale($var['mdResyncSize']*1024,$unit)." $unit";
    exec("$notify -e ".escapeshellarg("Unraid $last")." -s ".escapeshellarg("通知 [$server] - $last 已启动")." -d ".escapeshellarg("$info")." -i \"warning\"");
    $saved[$item][$name] = $last;
  }
} else {
  if ($last) {
    $duration = $var['sbSynced2'] - $var['sbSynced'];
    $status = $var['sbSyncExit'];
    $speed = $status==0 ? my_scale($var['mdResyncSize']*1024/$duration,$unit,1)." $unit/秒" : "不可用";
    list($entry,$duration,$speed,$status,$error) = explode('|', read_write_parity_log($var['sbSynced2'],$duration,$speed,$status,$var['sbSyncErrs']));
    $info = $status==0 ? "持续时间: ".my_check($duration, $speed) : ($status==-4 ? "已取消" : "错误代码: $status");
    $level = ($status==0 && $var['sbSyncErrs']==0) ? "normal" : "warning";
    exec("$notify -e ".escapeshellarg("Unraid $last")." -s ".escapeshellarg("通知 [$server] - $last 已完成 ($error 个错误)")." -d ".escapeshellarg("$info")." -i \"$level\"");
    unset($saved[$item][$name]);
  }
}

// check read-write status of USB flash drive
$name = 'flash';
$last = $saved[$item][$name] ?? '';
$warn = exec("grep -Pom1 '/boot \S+ \K\S{2}' /proc/mounts");
$info = "{$disks['flash']['id']} ({$disks['flash']['device']})";
if ($warn!="rw") {
  if ($warn!=$last) {
    exec("$notify -e \"USB flash 驱动器故障\" -s ".escapeshellarg("注意 [$server] - USB drive 不可读写")." -d ".escapeshellarg("$info")." -i \"alert\"");
    $saved[$item][$name] = $warn;
  }
} else {
  if ($last) {
    exec("$notify -e \"USB flash 正常运行\" -s ".escapeshellarg("通知 [$server] - USB drive 恢复正常运行")." -d ".escapeshellarg("$info"));
    unset($saved[$item][$name]);
  }
}

// check docker image disk utilization
system('mountpoint -q /var/lib/docker', $retval);
if ($retval===0) {
  $item = 'system';
  $name = 'docker';
  $last = $saved[$item][$name] ?? '';
  if (file_exists("/boot/config/docker.cfg")) {
    $cfg  = parse_ini_file("/boot/config/docker.cfg");
    $info = "Docker utilization of image file {$cfg['DOCKER_IMAGE_FILE']}";
  } else
    $info = "Docker image file not specified";

  $warn = exec("df /var/lib/docker|awk '/^\//{print $5*1}'");
  if ($warn>=$high1 && $high1>0) {
    if ($warn>$last) {
      exec("$notify -e \"Docker 临界的镜像磁盘使用率\" -s ".escapeshellarg("注意 [$server] - Docker 镜像磁盘使用率达到 ${warn}%")." -d ".escapeshellarg("$info")." -i \"alert\"");
      $saved[$item][$name] = $warn;
    }
  } elseif ($warn>=$high2 && $high2>0) {
    if ($warn>$last) {
      exec("$notify -e \"Docker 较高的镜像磁盘使用率\" -s ".escapeshellarg("警告 [$server] - Docker 镜像磁盘使用率达到 ${warn}%")." -d ".escapeshellarg("$info")." -i \"warning\"");
      $saved[$item][$name] = $warn;
    }
  } else {
    if ($last) {
      exec("$notify -e \"Docker 镜像磁盘使用率\" -s ".escapeshellarg("通知 [$server] - Docker 映像磁盘使用率恢复到正常水平")." -d ".escapeshellarg("$info"));
      unset($saved[$item][$name]);
    }
  }
}

// save new status
if ($saved) {
  $text = '';
  foreach ($saved as $item => $block) {
    if ($block) $text .= "[$item]\n";
    foreach ($block as $key => $value) $text .= "$key=\"$value\"\n";
  }
  if ($text) {
    if ($text != @file_get_contents($ram)) file_put_contents($ram, $text);
    if (!file_exists($rom) || exec("diff -q $ram $rom")) file_put_contents($rom, $text);
  } else {
    @unlink($ram);
    @unlink($rom);
  }
}
exit(0);
?>
